import React, { useEffect, useState } from 'react'
import { assign, queryTopReceiver } from '@/services/salaryManage/salaryConfirm'
import { isSuccess } from '@/utils/request';
import { Form, message, Modal, Spin, Tag } from 'antd'
import If from '@/components/If';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import { SearchInput } from '@/components/UserForm';
import { queryFeedbackEmployeeList } from '@/services/salaryManage/salaryCommon';

const AssignModal = Form.create()(({ form, visible, onOk, onCancel, model, organizationCode }) => {
    const [loading, setLoading] = useState(false);
    const [topReceivers, setTopReceivers] = useState([]);

    const handleOk = () => onOk(form.getFieldsValue(), form, model, setLoading);

    const acceptTopReceiver = topReceiver => {
        form.setFieldsValue({ employeeCode: topReceiver.employeeCode });
    };

    useEffect(() => {
        queryTopReceiver(organizationCode).then(response => {
            if (isSuccess(response)) {
                setTopReceivers(response.data);
            }
        });
        return () => {
            setTopReceivers([]);
        };
    }, []);

    return (
        <Modal
            title="分配接收人"
            visible={visible}
            okText="确认"
            onOk={handleOk}
            cancelText="取消"
            onCancel={onCancel}
            confirmLoading={loading}
        >
            <Spin spinning={loading}>
                <Form layout="horizontal" labelCol={{ span: 4 }} wrapperCol={{ span: 19 }}>
                    <Form.Item label="接收人" className={salaryStyle.mt22}>
                        <span>
                            {form.getFieldDecorator('employeeCode', {
                                rules: [{ required: true, message: '请选择接收人' }]
                            })(
                                <SearchInput
                                    getData={async () => {
                                        const response = await queryFeedbackEmployeeList({ organizationCode });
                                        const result = isSuccess(response)
                                            ? response.data || []
                                            : [];

                                        // 过滤掉不可用
                                        return result.filter(item => !item.disabled);
                                    }}
                                    selectProps={{
                                        placeholder: '请输入员工姓名',
                                        allowClear: true
                                    }}
                                    fieldsName={{
                                        value: 'employeeCode',
                                        title: 'name'
                                    }}
                                    style={{ width: '12.875em' }}
                                />
                            )}
                        </span>
                    </Form.Item>
                    {
                        topReceivers && topReceivers.length > 0
                            ? <Form.Item label="常用接收人">
                                <div>
                                    {topReceivers.map(receiverInfo => (
                                        <Tag
                                            key={receiverInfo.employeeCode}
                                            onClick={() => acceptTopReceiver(receiverInfo)}
                                            className={salaryStyle.noBorderTag}
                                            color="rgba(0, 0, 0, 0.05)"
                                            style={{ color: 'rgba(0, 0, 0, 0.65)' }}
                                        >{receiverInfo.name}</Tag>
                                    ))}
                                </div>
                            </Form.Item>
                            : null
                    }

                </Form>
            </Spin>
        </Modal>
    );
});
AssignModal.displayName = 'AssignModal';

/**
 *分配接收人
 * @param organizationCode
 * @param operateRecord
 * @param setOperateRecord
 * @param search
 */
const useAssign = (organizationCode, operateRecord, setOperateRecord, search) => {
    // 显示分配
    const [showAssign, setShowAssign] = useState(false);

    // 展示分配
    const onShowAssign = record => {
        setShowAssign(true);
        setOperateRecord(record);
    };
    // 分配
    const onAssign = (formValues, form, record, setModalLoading) => {
        form.validateFieldsAndScroll(errors => {
            if (errors) {
                return;
            }
            setModalLoading(true);
            assign({ id: record.id, employeeCode: formValues.employeeCode })
                .then(response => {
                    if (!isSuccess(response)) {
                        message.error(response.msg);
                        return;
                    }
                    message.success('分配成功');
                    search();
                    setShowAssign(false);
                })
                .finally(() => setModalLoading(false));
        });
    };

    return {
        onShowAssign,
        onAssign,
        render() {
            return (
                <>
                    <If condition={showAssign}>
                        <AssignModal
                            visible={showAssign}
                            onOk={onAssign}
                            onCancel={() => setShowAssign(false)}
                            model={operateRecord}
                            organizationCode={organizationCode}
                        />
                    </If>
                </>
            );
        }
    };
};

export default useAssign;
